<template>
  <NpDialog :visible.sync="dialogPvVisible" width="1160px" min-width="800px" class="container">
    <div class="title">新增/编辑设备</div>
    <div class="con g-bgc-fill-el-input">
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="86px">
        <el-form-item label="序列号" prop="deviceCode">
          <el-input v-model="ruleForm.deviceCode" placeholder="请输入序列号" :disabled="fromInputDisabled"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="menufacturerId">
          <el-select v-model="ruleForm.menufacturerId" placeholder="请选择品牌">
            <el-option v-for="(item, index) in brandOptions" :key="'br' + index" :label="item.menufacturer"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input v-model="ruleForm.deviceModel" placeholder="请输设备型号"></el-input>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="ruleForm.deviceName" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备容量" prop="storage">
          <div class="storage_warp">
            <el-input v-model="ruleForm.storage" placeholder="请输入设备容量" @input="storage_input"></el-input>
            <el-select v-model="ruleForm.storageUnit" placeholder="">
              <el-option v-for="item in ['TB', 'GB']" :key="item" :label="item" :value="item" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="CPU" prop="cpu">
          <el-input v-model="ruleForm.cpu" placeholder="请选择CPU"></el-input>
        </el-form-item>
        <el-form-item label="运行内存" prop="ram">
          <el-input v-model="ruleForm.ram" placeholder="请输入运行内存"></el-input>
        </el-form-item>
        <el-form-item label="屏幕尺寸" prop="screenSize">
          <el-input v-model="ruleForm.screenSize" placeholder="请输入屏幕尺寸"></el-input>
        </el-form-item>
        <el-form-item label="屏幕分辨率" prop="screenResolution">
          <el-input v-model="ruleForm.screenResolution" placeholder="请输入屏幕分辨率"></el-input>
        </el-form-item>
        <!-- 
          <el-form-item label="生产商" prop="">
            这一期不弄
            <el-input v-model="ruleForm.deviceBrand" placeholder="请输入生产商"></el-input>
          </el-form-item>
           -->
        <el-form-item label="出厂日期" prop="dateProduction">
          <el-date-picker v-model="ruleForm.dateProduction" format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss" type="date" placeholder="请选择出厂日期" align="right">
          </el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <div class="fotter">
      <el-button type="info" plain class="btn1" @click="uploadCancelClick">取消</el-button>
      <!-- :disabled="isModifiedData" -->
      <el-button type="warning" @click="uploadImportClick('ruleFormRef')" :loading="submitLoading">确定</el-button>
    </div>
  </NpDialog>
</template>
<script>
import NpDialog from "@/components/np/Dialog/index.vue"
import { updateDevice, batchImportDevices } from '@/api/equipment-management/list'
import { getMatchFormatNumber } from "@/utils"
export default {
  components: {
    NpDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    brandOptions: {
      type: Array,
      default: () => {
        return []
      }
    },
    infoRow: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    let com_blur__rule = [{ required: true, message: '此字段为必填。', trigger: 'blur' }],
      com_change__rule = [{ required: true, message: '此字段为必填。', trigger: 'change' }];
    return {
      dialogPvVisible: false,

      submitLoading: false,
      ruleForm: {
        deviceCode: '',
        menufacturerId: '',
        deviceModel: '',
        deviceName: '',
        storage: '',
        storageUnit: 'TB',// 容量单位，不传给后端
        cpu: '',
        ram: '',
        screenSize: '',
        screenResolution: '',
        dateProduction: '',
      },
      rules: {
        deviceCode: com_blur__rule,
        menufacturerId: com_change__rule,
      },
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogPvVisible = newVal;
        if (newVal) {
          if (this.infoRow) {
            this.editInfo()
            return
          }
        }
        if (!newVal) {
          this.resetFieldsFrom()
        }
      }
    }
  },
  computed: {
    isEdit() {
      return !!this.infoRow
    },
    isAdd() {
      return !this.infoRow
    },
    fromInputDisabled() {
      return this.isEdit
    },
    isModifiedData() {
      if (this.isEdit) {
        try {
          let arr = Object.keys(this.ruleForm);
          let v = arr.find(el => {
            let fd = this.ruleForm[el],
              rd = this.infoRow[el];
            if (!fd && !rd) {
              return false
            }
            return this.ruleForm[el] !== this.infoRow[el]
          })
          return !v
        } catch (error) { }
      }
      return false
    }
  },
  methods: {
    editInfo() {
      let arr = Object.keys(this.ruleForm);
      arr.forEach(el => {
        if (el === 'storage') {
          let radix = 1024, v = this.infoRow.storage;
          if (v >= radix) {
            let a = Number(v / radix).toFixed(3)
            this.ruleForm[el] = parseFloat(a) || this.ruleForm[el]
            return
          }
          this.ruleForm[el] = this.infoRow[el] || this.ruleForm[el]
          this.ruleForm.storageUnit = 'GB'
          return
        }
        this.ruleForm[el] = this.infoRow[el] || this.ruleForm[el]
      })
    },
    resetFieldsFrom() {
      Object.keys(this.ruleForm).forEach(el => {
        if (el === 'storageUnit') {
          this.ruleForm[el] = 'TB'
          return
        }
        this.ruleForm[el] = ''
      })
    },
    storage_input(e) {
      let v = getMatchFormatNumber(e)
      this.ruleForm.storage = v
    },
    uploadCancelClick() {
      this.dialogPvVisible = false
      this.$refs['ruleFormRef'].resetFields()
      this.$emit("update:visible", this.dialogPvVisible)
    },
    uploadImportClick(formName) {
      if (this.isModifiedData) {
        this.$message.error('数据未有更改，关闭当前弹窗。')
        this.uploadCancelClick()
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = { ...this.ruleForm }
          let is_trim_arr = ['deviceCode']
          console.log(222);
          for (let key in params) {
            console.log(key, is_trim_arr.includes(key));
            if (is_trim_arr.includes(key)) {
              console.log(params[key].trim() + '11111111');
              params[key] = params[key].trim()
            }
          }
          let fun = batchImportDevices
          if (this.isEdit) {
            params.id = this.infoRow.id || ''
            let b_v = this.brandOptions.find(el => {
              return el.id === this.ruleForm.menufacturerId
            })
            if (b_v) {
              params.deviceBrand = b_v.menufacturer
            }
            fun = updateDevice
          }
          if (this.isAdd) {
            // activedState 激活状态,U:未激活,A:已激活
            params.activedState = 'A'
            params = [params]
          }
          let data = this.isEdit ? 'edit' : 'add',
            obj = {
              add: '新增',
              edit: '编辑',
            };
          this.submitLoading = true
          fun(params).then(res => {
            if (res.code === 200) {
              this.$message.success(`${obj[data]}成功!`)
              setTimeout(() => {
                this.submitLoading = false
                this.uploadCancelClick()
                this.$emit("editSuccessChange", true)
              }, 2000)
              return
            } else {
              this.$message.error(`${obj[data]}失败。数据填写重复`)
            }
            this.submitLoading = false
          }).catch(err => {
            this.$message.error('系统错误，服务失败。')
            this.submitLoading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  }
}
</script>
<style lang="scss" scoped>
.title {
  padding-bottom: 32px;
  font-size: 18px;
  font-weight: 500;
  line-height: 24px;
  color: #15181D;
}

.fotter {
  padding-top: 12px;
  display: flex;
  justify-content: right;
  align-items: center;

  .btn1 {
    margin-right: 12px;
  }
}

.container {
  ::v-deep {
    @media (max-width: 1280px) {
      .np-el-d-body {
        width: calc(100% - 120px);
      }
    }
  }
}

::v-deep {
  .con {
    .el-form {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 0 40px;
    }

    .el-form-item__label {
      font-size: 14px;
      font-weight: normal;
      color: #8B8B8B;
    }

    .el-select,
    .el-date-editor {
      width: 100%;
    }
  }

  .storage_warp {
    display: grid;
    grid-template-columns: 3fr 1fr;
    gap: 0 10px;
  }
}
</style>